﻿using System.Collections.Generic;
using System.Threading.Tasks;
using GrapeCity.Forguncy.Commands;
using TencentCloud.Common;
using TencentCloud.Ocr.V20181119.Models;
using TencentCloudOcrPlugin.Resources;

namespace TencentCloudOcrPlugin.Ocr
{
    public class OcrIdCardAction : OcrActionBase
    {

        private static readonly Dictionary<string, string> ParamsDict = new Dictionary<string, string>();

        public OcrIdCardAction()
        {
            ParamsDict["Name"] = "姓名";
            ParamsDict["Sex"] = "性别";
            ParamsDict["Nation"] = "民族";
            ParamsDict["Birth"] = "出生日期";
            ParamsDict["Address"] = "地址";
            ParamsDict["IdNum"] = "身份证号";
            ParamsDict["Authority"] = "发证机关";
            ParamsDict["ValidDate"] = "证件有效期";
        }

        public override List<string> GetParamList(TencentCloudApiPropertyBase properties)
        {
            var list = base.GetParamList(properties);
            list.AddRange(ParamsDict.Values);
            return list;
        }
        
        public override async Task<Dictionary<string,object>> RunAsync(TencentCloudApiClientConfig clientConfig,
            IServerCommandExecuteContext dataContext, TencentCloudApiPropertyBase properties)
        {
            var ocrIdCardProperties = properties as OcrIdCardProperties;
            var baseRequest = await BuildRequestAsync(ocrIdCardProperties, dataContext);
            var request = new IDCardOCRRequest()
            {
                ImageUrl = baseRequest.ImageUrl,
                ImageBase64 = baseRequest.ImageBase64,
                CardSide = ocrIdCardProperties?.CardSide
            };
            var response = await GetClient(clientConfig).IDCardOCR(request);
            return BuildResp(response, properties);
        }
 
        private static Dictionary<string, object> BuildResp(AbstractModel tencentResp, TencentCloudApiPropertyBase properties) {
            var dict = new Dictionary<string, object>();
            if (!(tencentResp is IDCardOCRResponse response))
            {
                return dict;
            }
            if (properties.advancedSettings.TencentRawResp)
            {
                dict["原始数据"] = tencentResp;
            }
            var type = typeof(IDCardOCRResponse);
            foreach (var keyValuePair in ParamsDict)
            {
                dict[ParamsDict[keyValuePair.Key]]  = type.GetProperty(keyValuePair.Key)?.GetValue(response);
            }            
            return dict;
        }
    }
}